import 'package:flutter/material.dart';
import 'package:flutter1911/page/category_page.dart';
import 'package:flutter1911/page/member_page.dart';
import 'package:flutter/cupertino.dart';

import 'cart/cart_page.dart';
import 'home_page.dart';

/// AutomaticKeepAliveClientMixin 用于Flutter保持页面设置,哪个页面需要保持状态,就用混入with添加
/// 页面必须是StatefulWidget
/// 需要有2个前置的组件才能保持页面状态,PageView和IndexedStack
/// 重写wantKeepAlive方法,修改为true

class IndexPage extends StatefulWidget {
  const IndexPage({Key? key}) : super(key: key);

  @override
  _IndexPageState createState() => _IndexPageState();
}

class _IndexPageState extends State<IndexPage> {
  PageController? _pageController;

  final List<BottomNavigationBarItem> bottomTabs = [
    const BottomNavigationBarItem(icon: Icon(CupertinoIcons.home), label: '首页'),
    const BottomNavigationBarItem(
        icon: Icon(CupertinoIcons.search), label: '分类'),
    const BottomNavigationBarItem(
        icon: Icon(CupertinoIcons.shopping_cart), label: '购物车'),
    const BottomNavigationBarItem(
        icon: Icon(CupertinoIcons.profile_circled), label: '会员中心'),
  ];

  final List tabBodies = [
    const HomePage(),
    const CategoryPage(),
    const CartPage(),
    const MemberPage()
  ];

  int currentIndex = 0;
  var currentPage;

  @override
  void initState() {
    currentPage = tabBodies[currentIndex];
    _pageController = PageController()
      ..addListener(() {
        if (currentPage != _pageController?.page?.round()) {
          setState(() {
            currentPage = _pageController?.page?.round();
          });
        }
      });
    super.initState();
  }

  @override
  Widget build(BuildContext context) {
    return Scaffold(
      backgroundColor: const Color.fromRGBO(244, 245, 245, 1.0),
      bottomNavigationBar: BottomNavigationBar(
        selectedItemColor: Colors.pink,
        type: BottomNavigationBarType.fixed,
        currentIndex: currentIndex,
        items: bottomTabs,
        onTap: (index) {
          //每当点击导航栏Item时,切换页面的状态,从而展示不同的页面
          setState(() {
            currentIndex = index;
            currentPage = tabBodies[currentIndex];
          });
        },
      ),
      body: IndexedStack(
        index: currentIndex,
        children: const [HomePage(), CategoryPage(), CartPage(), MemberPage()],
      ),
    );
  }
}
